package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.health.dao.MemberDao;
import com.itheima.health.pojo.Member;
import com.itheima.health.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 会员SERVICE实现类
 */
@Service(interfaceClass = MemberService.class)
@Slf4j
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberDao memberDao;

    @Transactional
    @Override
    public Member addIfNotExist(Member member) {
        log.info("[会员-添加]data:{}",member);
        Member pojo = memberDao.selectPhoneNumber(member.getPhoneNumber());
        if(null != pojo) {
            //会员已添加，直接返回
            return pojo;
        }
        //调用DAO插入数据
        memberDao.insert(member);
        return memberDao.selectById(member.getId());
    }

    @Override
    public Member findById(Integer id) {

        return memberDao.selectById(id);
    }

    @Override
    public List<Integer> countByMonth(List<String> months) {
        List<Integer> resultLIst = new ArrayList<>();
        for (String month : months) {
            String endDate = month+".31";
            Long count = memberDao.countByRegTimeBefore(endDate);
            resultLIst.add(count.intValue());
        }
        return resultLIst;
    }

    @Override
    public List<Map<String, Object>> countByName() {
        return memberDao.countByName();
    }

    @Override
    public List<Map<String, Object>> countByAge() {
        String year = "";
        String month = "";
        String day = "";

        //判断生日是否为空
        List<Integer> list = memberDao.selectBirthday();
        for (Integer id : list) {
            List<String> idCard = memberDao.selectIdCardById(id);

            for (String s : idCard) {
                if (s.length() ==18){
                    try {
                        year = s.substring(6, 10);
                        month = s.substring(10, 12);
                        day = s.substring(12, 14);
                        String dateString = year + "-" + month + "-" + day;

                        Calendar cal = Calendar.getInstance();
                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                        Date date = df.parse(dateString);
                        //将已经转化的日期 插入到birthday中
                        memberDao.updateBirthdayById(id, date);

                    } catch (ParseException e) {
                        e.printStackTrace();
                        log.error("会员身份证转换日期错误");
                    }
                }
            }
        }

        return memberDao.selectByBirthday();
    }
}
